package com.jcoinexchange.web.auth;

import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * @desc auth interceptor
 *
 * @author tony
 */

public class AuthInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class.getName());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //解码token
        String token = request.getHeader(AuthConstant.AUTH_FLAG_HEADER_KEY);
        if(token != null){
            try{
                Claims parse = JwtUtils.parse(token);
                String userInfoString = (String) parse.get(AuthConstant.USER_INFO);
                UserInfo userInfo = JSON.parseObject(userInfoString, UserInfo.class);
                Auth.fill(userInfo,token);
            }catch (Exception e){
                logger.error("user auth info parse error :{}", e.toString());
                logger.error("invalid token:{}", token);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Auth.clear();
    }
}
